<template>
	<view class="evaluation-page">
		<nav-header title="自我评价"></nav-header>

		<view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
			<!-- Description -->
			<view class="description-section">
				<text class="title">个人优势和自我评价</text>
				<text class="subtitle">简单描述你的个人特点、优势和能力，让HR快速了解你</text>
			</view>
			<!-- AI生成按钮 -->
			<view class="ai-generate">
				<button class="generate-btn" @click="generateEvaluation">
					<text class="generate-icon">✨</text>
					AI生成
				</button>
			</view>
			<!-- Text Editor -->
			<view class="editor-section">
				<textarea class="evaluation-textarea" v-model="formData.content"
					placeholder="例如：我是一名拥有3年工作经验的前端开发工程师，擅长Vue.js和React框架，注重代码质量和用户体验。我有良好的团队合作精神，能快速适应新环境和技术栈..."
					:maxlength="maxLength"></textarea>
				<view class="word-count">{{ formData.content.length }}/{{ maxLength }}</view>
			</view>
			<!-- Tips -->
			<view class="tips-section">
				<view class="tips-header">
					<u-icon name="info-circle" color="#5ac725" size="18"></u-icon>
					<text>写作建议</text>
				</view>
				<view class="tips-content">
					<view class="tip-item">• 突出你的专业技能和核心竞争力</view>
					<view class="tip-item">• 结合简历其他模块，避免重复内容</view>
					<view class="tip-item">• 使用简洁、专业的语言</view>
					<view class="tip-item">• 可以适当提及一些软技能和个人特点</view>
				</view>
			</view>
		</view>

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" background-color="#fff" mask-background-color="rgba(0,0,0,0)" :is-mask-click="false"
				type="bottom" borderRadius='20px 20px 0 0 '>
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">AI生成</text>
						<uni-icons type="closeempty" size="24" @click="closePopup"></uni-icons>
					</view>
					<view class="popup-body">
						<text>{{AIContent}}</text>
					</view>
					<view class="popup-footer">
						<button class="popup-btn" @click="rewriteEvaluation">重写</button>
						<button type="primary" class="popup-btn" @click="replaceEvaluation">替换</button>
					</view>
				</view>
			</uni-popup>
		</view>

		<!-- Save Button -->
		<view class="action-bar">
			<button class="save-btn" @click="saveEvaluation">保存</button>
		</view>
		
		<view class="bottom">
			<!-- Delete Button -->
			<view class="delete-action" v-if="!isAdding">
				<button class="delete-btn" @click="confirmDelete">删除</button>
			</view>
			<!-- Save Button -->
			<view class="action-bar">
				<button class="save-btn" @click="saveEvaluation">保存</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue'
	import {
		useResumeStore
	} from '@/store/resume.js'
	import NavHeader from '@/components/nav-header.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getSelfEvaluationList,
		getSelfEvaluationDetail,
		addSelfEvaluation,
		updateSelfEvaluation,
		generateSelfEvaluation
	} from '@/api/edit/evaluation'
	import env from '@/env'
	import { useAuthStore } from '@/store/index';
	import { mockInterviewWebSocketProcess } from '@/api/ai'
	import { useWebSocket } from '@/utils/useWebSocket'
	
	const authStore = useAuthStore();
	const resumeStore = useResumeStore()
	const statusBarHeight = ref(20)
	const maxLength = 800
	const isAdding = ref(true)
	const currentId = ref(null)
	const popup = ref(null)
	const AIContent = ref('')
	const isGenerating = ref(false)
	const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)
	
	// 注册WebSocket消息处理函数
	onMessage((data) => {
		uni.hideLoading();
		try {
			if (typeof data === 'string') {
				try {
					const parsedData = JSON.parse(data);
					if (parsedData.topic === 'SELF_EVALUATION') {
						if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
							isGenerating.value = false;
							uni.hideLoading();
							uni.showToast({
								title: '生成完成',
								icon: 'success'
							});
							return;
						}
						AIContent.value += parsedData.content;
						return;
					}
				} catch (e) {
					// 如果不是JSON格式，直接处理字符串
					if (data === '[DONE]' || data.includes('[DONE]')) {
						isGenerating.value = false;
						uni.hideLoading();
						uni.showToast({
							title: '生成完成',
							icon: 'success'
						});
						return;
					}
					AIContent.value += data;
				}
			}
		} catch (error) {
			console.error('处理WebSocket消息出错:', error);
		}
	});
	
	// 表单数据
	const formData = reactive({
		content: '',
		resumeId: resumeStore.resumeId
	})

	const getEvaluationDetail = async (id) => {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			const res = await getSelfEvaluationDetail(id)
			if (res.code === 200) {
				formData.content = res.data.selfEvaluationContent || ''
			}
		} catch (error) {
			console.error('获取自我评价详情失败', error)
		} finally {
			uni.hideLoading()
		}
	}

	onLoad((options) => {
		if (options.index) {
			currentId.value = options.index
			isAdding.value = false
			getEvaluationDetail(options.index)
		}else {
			isAdding.value = true
		}
	})

	onMounted(() => {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync()
		statusBarHeight.value = systemInfo.statusBarHeight
		
		// 启动时先尝试连接WebSocket
		try {
			connect().then(() => {
				console.log('WebSocket连接成功，可以接收消息');
			}).catch(err => {
				console.error('WebSocket连接失败:', err);
			});
		} catch (e) {
			console.error('连接WebSocket异常:', e);
		}
	})

	onUnmounted(() => {
		// 关闭WebSocket连接
		close();
		if (isGenerating.value) {
			isGenerating.value = false;
		}
	})

	// 使用AI生成自我评价
	const generateEvaluation = async () => {
		try {
			// 避免重复请求
			if (isGenerating.value) {
				return;
			}
			
			isGenerating.value = true;
			AIContent.value = ''; // 清空之前的内容
			popup.value.open();
			
			uni.showLoading({
				title: 'AI生成中...'
			});
			
			// 创建请求数据
			const requestData = {
				type: 'SELF_EVALUATION',
				aiResumeSelfEvaluationBo: {
					resumeId: resumeStore.resumeId
				}
			};
			
			// 检查WebSocket连接状态
			if (!isConnected.value) {
				console.log('WebSocket未连接，尝试连接...');
				await connect();
				console.log('WebSocket连接已建立');
			} else {
				console.log('WebSocket已连接，状态正常');
			}
			
			// 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
			console.log('准备调用HTTP接口触发后端推送...');
			
			// 调用HTTP接口触发后端推送WebSocket消息
			mockInterviewWebSocketProcess(requestData).then(res => {
				// 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
				setTimeout(() => {
					if (isGenerating.value && !AIContent.value) {
						console.log('未收到WebSocket消息，使用传统方式');
					}
				}, 5000); // 5秒后检查
				
			}).catch(err => {
				console.error('调用HTTP接口失败:', err);
				isGenerating.value = false;
				uni.hideLoading();
				uni.showToast({
					title: '生成失败',
					icon: 'none'
				});
			});
			
		} catch (error) {
			console.error('生成自我评价失败', error);
			isGenerating.value = false;
			uni.hideLoading();
			uni.showToast({
				title: '生成失败',
				icon: 'none'
			});
		}
	}

	// 保存自我评价
	const saveEvaluation = async (showTips = true) => {
		if (!formData.content.trim()) {
			if (showTips) {
				uni.showToast({
					title: '请输入自我评价',
					icon: 'none'
				})
			}
			return false
		}
		try {
			if (showTips) {
				uni.showLoading({
					title: '保存中...'
				})
			}
			let res
			const params = {
				selfEvaluationContent: formData.content,
				resumeId: resumeStore.resumeId
			}
			if (isAdding.value) {
				// 新增模式
				res = await addSelfEvaluation(params)
			} else {
				// 编辑模式
				params.id = currentId.value
				res = await updateSelfEvaluation(params)
			}
			
			if (res.code === 200) {
				// 更新store中的数据
				resumeStore.selfEvaluation = formData.content
				if (showTips) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
				return true
			} else {
				if (showTips) {
					uni.showToast({
						title: res.msg || '保存失败',
						icon: 'none'
					})
				}
				return false
			}
		} catch (error) {
			console.error('保存自我评价失败', error)
			if (showTips) {
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
			return false
		} finally {
			if (showTips) {
				uni.hideLoading()
			}
		}
	}

	// 关闭AI生成弹窗
	const closePopup = () => {
		popup.value.close();
		isGenerating.value = false;
		uni.hideLoading();
	}

	// 重写AI生成内容
	const rewriteEvaluation = () => {
		isGenerating.value = false;
		setTimeout(() => {
			generateEvaluation();
		}, 300);
	}

	// 替换AI生成内容
	const replaceEvaluation = () => {
		popup.value.close();
		formData.content = AIContent.value;
		isGenerating.value = false;
	}
</script>

<style lang="scss" scoped>
	.evaluation-page {
		min-height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;

		.content {
			flex: 1;
			padding: 20px;
			padding-bottom: 100px;

			.description-section {
				margin-bottom: 20px;

				.title {
					font-size: 20px;
					font-weight: bold;
					color: #333;
					margin-bottom: 8px;
					display: block;
				}

				.subtitle {
					font-size: 14px;
					color: #999;
					display: block;
				}
			}

			.editor-section {
				position: relative;
				margin-bottom: 35px;

				.evaluation-textarea {
					height: 180px;
					border: 1px solid #e5e5e5;
					border-radius: 8px;
					padding: 15px;
					font-size: 16px;
					line-height: 1.5;
					background-color: #f9f9f9;
				}

				.word-count {
					position: absolute;
					bottom: -20px;
					right: 10px;
					font-size: 12px;
					color: #999;
				}
			}

			.ai-generate {
				margin-bottom: 20px;
				display: flex;
				justify-content: flex-end;

				.generate-btn {
					display: inline-block;
					background-color: #f0f7ff;
					color: #4080ff;
					border-radius: 20px;
					font-size: 14px;
					border: none;
					margin: unset;

					.generate-icon {
						margin-right: 4px;
					}
				}
			}

			.tips-section {
				background-color: #f8f8f8;
				border-radius: 8px;
				padding: 15px;

				.tips-header {
					display: flex;
					align-items: center;
					margin-bottom: 10px;

					text {
						margin-left: 6px;
						font-size: 16px;
						font-weight: 500;
						color: #333;
					}
				}

				.tips-content {
					color: #666;
					font-size: 14px;

					.tip-item {
						margin-bottom: 6px;
						line-height: 1.5;
					}
				}
			}
		}

		.delete-action {

			.delete-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				text-align: center;
				border-radius: 22px;
				font-size: 16px;
				color: #ff4d4f;
				background-color: #fff;
				border: 1px solid #ff4d4f;
			}
		}

		.action-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 10px 20px;
			box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
			z-index: 9;

			.save-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				background-color: #5ac725;
				color: #fff;
				font-size: 16px;
				font-weight: 500;
				border-radius: 22px;
			}
		}

		.popup-content {
			padding: 20px;
			border-radius: 20px 20px 0 0;
			border-top: 1px solid #e5e5e5;

			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.popup-title {
					font-size: 16px;
					font-weight: 500;
				}
			}

			.popup-body {
				font-size: 14px;
				line-height: 1.5;
				padding: 20px 0;
				height: 200px;
				overflow-y: auto;
			}

			.popup-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #fff;
			}

			.popup-footer button {
				display: inline-block;
				margin: unset;
				font-size: 14px;
			}
		}
	}
</style>